package mp

import (
	"context"
	"strings"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListLogic) UserList(req *types.UserSearch) (resp *types.UserList, err error) {
	var datas []models.User
	conds := xb.And(xb.Gt{"id": 1})
	// conds := xb.And(xb.Gt{"id": 0})
	if req.Keyword != "" {
		conds = conds.And(xb.Like{"username", "'%" + req.Keyword + "%'"}.Or(xb.Like{"name", "'%" + req.Keyword + "%'"}).Or(xb.Like{"mobile", "'%" + req.Keyword + "%'"}))
	}
	if req.DeptId != 0 {
		conds = conds.And(xb.Eq{"dept_id": req.DeptId})
	}
	if req.IsUse != 0 {
		conds = conds.And(xb.Eq{"is_use": req.IsUse})
	}

	total := db.CountData(&models.User{}, conds)

	depts := db.DeptMap()

	db.FindPageDatas(&datas, conds, req.Page)
	items := []types.User{}
	for _, v := range datas {
		tmp := types.User{}
		copier.Copy(&tmp, &v)
		deptTitle := []string{}
		for _, iv := range strings.Split(v.DeptTier, ",") {
			if iv == "" || iv == "0" {
				continue
			}
			itid := utils.StringToInt(iv)
			if itVa, ok := depts[itid]; ok {
				deptTitle = append(deptTitle, itVa.Title)
			}
		}
		tmp.DeptTitle = strings.Join(deptTitle, "/")
		items = append(items, tmp)
	}
	return &types.UserList{
		Total: int(total),
		Items: items,
	}, nil
}
